package com.th.common.captcha.service.impl;

import cn.hutool.captcha.LineCaptcha;
import com.th.common.captcha.service.GraphicCaptchaService;
import com.th.common.constant.Constants;
import com.th.common.exception.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

/**
 * @author tuhang
 */
@Service
public class GraphicCaptchaServiceImpl implements GraphicCaptchaService {
    /**
     * 默认图形验证码过期时间
     */
    public static final int DEFAULT_TIMEOUT = 5;

    /**
     * 默认图形验证码过期时间单位
     */
    public static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.MINUTES;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String generate(String id, OutputStream outputStream) {
        LineCaptcha captcha = new LineCaptcha(150, 50);
        // 写出到response中
        captcha.write(outputStream);

        return captcha.getCode();
    }

    @Override
    public void save(String id, String captcha) {
        save(id, captcha, DEFAULT_TIMEOUT, DEFAULT_TIME_UNIT);
    }

    @Override
    public void save(String id, String captcha, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(Constants.GRAPHIC_CAPTCHA_CODES + id, captcha, timeout, unit);
    }

    @Override
    public boolean verify(String id, String captcha) {
        String captchaInRedis = (String) redisTemplate.opsForValue().get(Constants.GRAPHIC_CAPTCHA_CODES + id);

        if (!StringUtils.hasLength(captchaInRedis)) {
            throw new BadRequestException("未发送验证码");
        }

        if (!captchaInRedis.equalsIgnoreCase(captcha)) {
            throw new BadRequestException("验证码错误");
        }

        return true;
    }

    @Override
    public void remove(String id) {
        redisTemplate.delete(Constants.GRAPHIC_CAPTCHA_CODES + id);
    }
}
